package com.artron.mediaartron.ui.fragment.order;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alipay.sdk.app.PayTask;
import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.image.ImageUtils;
import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.AddressData;
import com.artron.mediaartron.data.entity.AliPayResult;
import com.artron.mediaartron.data.entity.DefaultAddressData;
import com.artron.mediaartron.data.entity.FrameData;
import com.artron.mediaartron.data.entity.ImageData;
import com.artron.mediaartron.data.entity.Invoice;
import com.artron.mediaartron.data.entity.OrderData;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.entity.WeChatData;
import com.artron.mediaartron.data.entity.Works;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.net.api.OrderAddressApi;
import com.artron.mediaartron.data.production.FrameConstant;
import com.artron.mediaartron.data.production.SuitableSizeHelper;
import com.artron.mediaartron.data.task.OrderTask;
import com.artron.mediaartron.ui.activity.CustomSelectionActivity;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.helper.ThrottleFirstClickHelper;
import com.artron.mediaartron.util.TextSpanUtils;
import com.artron.mediaartron.util.TextSpanUtils.TextSpan;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-18.
 */

public class OrderFragment extends BaseStaticFragment implements View.OnClickListener {

    private static final String TAG = "OrderFragment";

    @BindView(R.id.OrderFragment_tv_name)
    protected TextView mTvName;
    @BindView(R.id.OrderFragment_tv_tel_num)
    protected TextView mTvTelNum;
    @BindView(R.id.OrderFragment_tv_address)
    protected TextView mTvAddress;
    @BindView(R.id.OrderFragment_tv_tag)
    protected TextView mTvTag;
    @BindView(R.id.OrderFragment_rl_user_info)
    protected RelativeLayout mRlContainerUserInfo;
    @BindView(R.id.OrderFragment_ll_no_info)
    protected LinearLayout mLlContainerNoInfo;
    @BindView(R.id.OrderFragment_iv_image)
    protected ImageView mIvImage;
    @BindView(R.id.OrderFragment_fl_frame)
    protected FrameLayout mFlFrame;
    @BindView(R.id.OrderFragment_tv_image_name)
    protected TextView mTvImageName;
    @BindView(R.id.OrderFragment_tv_image_type)
    protected TextView mTvImageType;
    @BindView(R.id.OrderFragment_tv_image_size)
    protected TextView mTvImageSize;
    @BindView(R.id.OrderFragment_tv_image_frame_name)
    protected TextView mTvFrameName;
    @BindView(R.id.OrderFragment_tv_image_price)
    protected TextView mTvImagePrice;
    @BindView(R.id.OrderFragment_tv_image_number)
    protected TextView mTvImageNum;
    @BindView(R.id.OrderFragment_tv_number_minus)
    protected TextView mTvNumberMinus;
    @BindView(R.id.OrderFragment_tv_number)
    protected TextView mTvNumber;
    @BindView(R.id.OrderFragment_tv_number_add)
    protected TextView mTvNumberAdd;
    @BindView(R.id.OrderFragment_tv_price)
    protected TextView mTvPrice;
    @BindView(R.id.OrderFragment_tb_weixin)
    protected ToggleButton mTbWeixin;
    @BindView(R.id.OrderFragment_ll_weixin)
    protected LinearLayout mLlWeixin;
    @BindView(R.id.OrderFragment_tb_zhifubao)
    protected ToggleButton mTbZhifubao;
    @BindView(R.id.OrderFragment_ll_zhifubao)
    protected LinearLayout mLlZhifubao;
    @BindView(R.id.OrderGeneral_tv_price)
    protected TextView mTvAllPrice;
    @BindView(R.id.OrderGeneral_tv_ensure)
    protected Button mTvEnsure;
    @BindView(R.id.OrderFragment_fl_invoice)
    protected FrameLayout mFlInvoice;
    @BindView(R.id.OrderFragment_tv_invoice)
    protected TextView mTvInvoice;
    private FrameData mData;
    private DefaultAddressData mDefaultAddress;
    private Invoice mInvoice;
    private Works mWorks;
    private int mCurrentPrice;
    private OrderData mOrderData;

    public static OrderFragment newInstance() {
        Bundle args = new Bundle();
        OrderFragment fragment = new OrderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initVariable() {
        SuitableSizeHelper helper = SuitableSizeHelper.getHelper();
        mData = helper.getFrameData();
        mWorks = helper.getWorks();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_order;
    }

    @Override
    protected void initView() {
        queryDefaultAddress();

        mLlContainerNoInfo.setOnClickListener(this);
        mRlContainerUserInfo.setOnClickListener(this);

        initFrameImage();
        initOtherView();

    }

    private void initOtherView() {
        //修改地址
        mRlContainerUserInfo.setOnClickListener(this);
        mLlContainerNoInfo.setOnClickListener(this);

        //设置增加和减少购买数量的点击事件
        mTvNumberAdd.setOnClickListener(this);
        mTvNumberMinus.setOnClickListener(this);

        //发票
        mFlInvoice.setOnClickListener(this);

        //微信支付宝按钮点击事件
        mLlWeixin.setOnClickListener(this);
        mLlZhifubao.setOnClickListener(this);
        mTbWeixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mTbZhifubao.isChecked() && isChecked) {
                    mTbZhifubao.setChecked(false);
                }
                if (!mTbZhifubao.isChecked() && !isChecked) {
                    mTbWeixin.setChecked(true);
                }
            }
        });

        mTbZhifubao.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mTbWeixin.isChecked() && isChecked) {
                    mTbWeixin.setChecked(false);
                }
                if (!mTbWeixin.isChecked() && !isChecked) {
                    mTbZhifubao.setChecked(true);
                }
            }
        });


        //价格相关
        mTvPrice.setText("￥" + mData.getPrice());
        String numberStr = mTvNumber.getText().toString();
        final int number = Integer.parseInt(numberStr);
        mData.setNumber(number);
        mCurrentPrice = number * mData.getPrice();
        setCurrentPrice(mData.getPrice());

        //确定订单
    //        mTvEnsure.setOnClickListener(this);
        ThrottleFirstClickHelper.throttleFirst(mTvEnsure, this);

        mTvImageNum.setVisibility(View.GONE);
    }

    private void setCurrentPrice(int price) {
        TextSpanUtils.setTextWithSpan(mTvAllPrice,
                TextSpan.holder("应付：", new ForegroundColorSpan(UIUtils.getColor(R.color.gray_66))),
                TextSpan.holder("￥", new AbsoluteSizeSpan(12, true)),
                TextSpan.holder(price + ".", new AbsoluteSizeSpan(18, true)),
                TextSpan.holder("00", new AbsoluteSizeSpan(12, true)));
    }

    /**
     * 绑定中间框画图片相关数据
     */
    private void initFrameImage() {
        initImageWidthAndHeight(mFlFrame, mIvImage);
        SuitableSizeHelper helper = SuitableSizeHelper.getHelper();
        Bitmap clipBitmap = helper.getClipBitmap();
        ImageData image = mData.getImage();
        if (clipBitmap != null) {
            mIvImage.setImageBitmap(clipBitmap);
        } else {
            ImageUtils.setUrl(mIvImage, image.getContentImage());
        }

        mTvImageName.setText(mData.getTitle());
        if (mData.getType() == CustomSelectionActivity.CUSTOM_MADE) {
            mTvImageType.setText("框画");
        } else if (mData.getType() == CustomSelectionActivity.POSTER) {
            mTvImageType.setText("海报");
        }
        mTvImageSize.setText(mData.getShowSize());
        mTvFrameName.setText(mData.getShapeType());
        TextSpanUtils.setTextWithSpan(mTvImagePrice,
                TextSpan.holder("￥", new AbsoluteSizeSpan(12, true)),
                TextSpan.holder(mData.getPrice() + ".", new AbsoluteSizeSpan(18, true)),
                TextSpan.holder("00", new AbsoluteSizeSpan(12, true)));
    }

    /**
     * 查询默认地址
     */
    private void queryDefaultAddress() {
        setVisibleAddressInfo(true);
        User user = AppProfile.getUserInfo().getUser();
        OrderAddressApi api = RetrofitHelper.getOrderAddressApi();
        RetrofitHelper.subscript(api.queryDefaultAddress(user.getPassId()),
                new Action1<Response<DefaultAddressData>>() {

                    @Override
                    public void call(Response<DefaultAddressData> response) {
                        if (response != null && "1".equals(response.getStatus())
                                && response.getData() != null) {

                            mDefaultAddress = response.getData();
                            if (TextUtils.isEmpty(mDefaultAddress.getName()) ||
                                    TextUtils.isEmpty(mDefaultAddress.getMobileCode()) ||
                                    TextUtils.isEmpty(mDefaultAddress.getDetail())) {
                                return;
                            }
                            setDefaultAddressContent();
                        }
                    }
                });
    }

    private void setDefaultAddressContent() {
        mTvName.setText(mDefaultAddress.getName());
        mTvTelNum.setText(mDefaultAddress.getMobileCode());
        mTvAddress.setText(mDefaultAddress.getDetail());
        mTvTag.setVisibility(mDefaultAddress.isDefault() ? View.VISIBLE : View.INVISIBLE);
        setVisibleAddressInfo(false);
    }

    /**
     * 隐藏或者显示默认地址
     */
    private void setVisibleAddressInfo(boolean isVisible) {
        int visible = isVisible ? View.GONE : View.VISIBLE;
        int gone = !isVisible ? View.GONE : View.VISIBLE;

        mRlContainerUserInfo.setVisibility(visible);
        mLlContainerNoInfo.setVisibility(gone);
    }

    private void addOrMinus(int per) {
        String number = mTvNumber.getText().toString();
        int intNumber = Integer.parseInt(number);
        if (intNumber != 1 || per > 0) {
            intNumber += per;
            mTvNumber.setText(String.valueOf(intNumber));
        }
        mCurrentPrice = intNumber * mData.getPrice();
        mData.setNumber(intNumber);
        setCurrentPrice(mCurrentPrice);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.OrderFragment_tv_number_add:
                addOrMinus(1);
                break;
            case R.id.OrderFragment_tv_number_minus:
                addOrMinus(-1);
                break;
            case R.id.OrderFragment_ll_weixin:
                mTbWeixin.setChecked(true);
                break;
            case R.id.OrderFragment_ll_zhifubao:
                mTbZhifubao.setChecked(true);
                break;
            case R.id.OrderGeneral_tv_ensure:
                ensureOrder();
                break;
            case R.id.OrderFragment_fl_invoice:
                GeneralActivity.startForResult(mContext, GeneralActivity.INVOICE, "发票", mInvoice);
                break;
            case R.id.OrderFragment_rl_user_info:
            case R.id.OrderFragment_ll_no_info:
                GeneralActivity.startForResult(mContext, GeneralActivity.ORDER_ADDRESS,
                        "收货地址");
                break;
        }
    }

    private void ensureOrder() {
        if (mDefaultAddress == null || TextUtils.isEmpty(mDefaultAddress.getId())
                || TextUtils.isEmpty(mDefaultAddress.getMobileCode())) {
            ToastUtil.show("收获地址不能为空");
            return;
        }


        String number = mTvNumber.getText().toString();
        try {
            int i = Integer.parseInt(number);
            mWorks.setWorksQuantity(i);
        } catch (Exception e) {
            Log.e(TAG, "ensureOrder: ", e);
        }
        OrderTask.createRapidOrder("", mDefaultAddress.getId(), 0, mInvoice, mWorks)
                .flatMap(new Func1<Response<OrderData>, Observable<Response<WeChatData>>>() {
                    @Override
                    public Observable<Response<WeChatData>> call(Response<OrderData> response) {
                        if (response != null && response.getData() != null) {
                            mOrderData = response.getData();
                            SuitableSizeHelper.getHelper().setOrderId(mOrderData.getId());
                            String code = mOrderData.getCode();
                            if (mTbZhifubao.isChecked()) {
                                return RetrofitHelper.getHostApi().getAlipayData(code, mCurrentPrice + "", "传给雅昌")
                                        .map(new Func1<Response<String>, Response<WeChatData>>() {
                                            @Override
                                            public Response<WeChatData> call(Response<String> response) {
                                                Response<WeChatData> result = new Response<>();
                                                WeChatData data = new WeChatData();
                                                data.setAlipayStr(response.getData());
                                                result.setData(data);
                                                return result;
                                            }
                                        });
                            } else {
                                return RetrofitHelper.getHostApi().getWeChatData(code, mCurrentPrice + "");
                            }
                        }
                        return null;
                    }
                })
                .flatMap(new Func1<Response<WeChatData>, Observable<AliPayResult>>() {
                    @Override
                    public Observable<AliPayResult> call(Response<WeChatData> response) {
                        if (response == null || response.getData() == null) {
                            return null;
                        }

                        final WeChatData data = response.getData();
                        if (mTbZhifubao.isChecked()) {
                            return Observable.create(new Observable.OnSubscribe<AliPayResult>() {
                                @Override
                                public void call(Subscriber<? super AliPayResult> subscriber) {
                                    try {
                                        PayTask aliPay = new PayTask(getActivity());
                                        String aliPayStr = data.getAlipayStr();
                                        Map<String, String> result = aliPay.payV2(aliPayStr, true);
                                        subscriber.onNext(new AliPayResult(result));
                                    } catch (Exception e) {
                                        MobclickAgent.reportError(UIUtils.getContext(), e);
                                        subscriber.onError(e);
                                    } finally {
                                        subscriber.onCompleted();
                                    }
                                }
                            });
                        } else {
                            SuitableSizeHelper.getHelper().setStartPayDetail(true);
                            IWXAPI wxApi = WXAPIFactory.createWXAPI(mContext, null);
                            wxApi.registerApp(data.getAppid());
                            PayReq request = new PayReq();
                            request.appId = data.getAppid();
                            request.partnerId = data.getMch_id();
                            request.prepayId = data.getPrepay_id();
                            request.packageValue = data.getPackageX();
                            request.nonceStr = data.getNonce_str();
                            request.timeStamp = data.getTimestamp() + "";
                            request.sign = data.getSecondSignature();
                            wxApi.sendReq(request);
                        }
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Action1<AliPayResult>() {
                    @Override
                    public void call(AliPayResult result) {
                        if (result != null) {
                            if (result.getResult() != null
                                    && "9000".equals(result.getResultStatus())) {
                                GeneralActivity.start(mContext, GeneralActivity.ORDER_SUCCESS,
                                        "支付成功", mOrderData.getId());
                            } else {
                                GeneralActivity.start(mContext, GeneralActivity.ORDER_DETAIL,
                                        "订单详情",  mOrderData.getId());
                                ToastUtil.show("支付失败");
                            }
                            SuitableSizeHelper.getHelper().setDefaultAddress(mDefaultAddress);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        MobclickAgent.reportError(UIUtils.getContext(), throwable);
                    }
                });

    }

    private void initImageWidthAndHeight(View ivFrame, ImageView ivImage) {
        ViewGroup.LayoutParams frameParams = ivFrame.getLayoutParams();

        int heightSpec = View.MeasureSpec.makeMeasureSpec(frameParams.height,
                View.MeasureSpec.EXACTLY);
        int widthSpec = View.MeasureSpec.makeMeasureSpec(frameParams.width,
                View.MeasureSpec.EXACTLY);
        ivFrame.measure(widthSpec, heightSpec);

        float frameWidth = ivFrame.getMeasuredWidth();

        float per = frameWidth / Math.max(mData.getWidth(), mData.getHeight());

        ViewGroup.LayoutParams imageParams = ivImage.getLayoutParams();
        imageParams.height = (int) ((mData.getHeight() - FrameConstant.BLANK_CUSTOM_MADE) * per);
        imageParams.width = (int) ((mData.getWidth() - FrameConstant.BLANK_CUSTOM_MADE) * per);
        ivImage.setLayoutParams(imageParams);
    }

    public void setDefaultAddress(AddressData data) {
        if (data != null && TextUtils.isEmpty(data.getName())
                && TextUtils.isEmpty(data.getMobileCode())) {
            setVisibleAddressInfo(true);
            mDefaultAddress = null;
        } else {
            mDefaultAddress.setAddress(data);
            setDefaultAddressContent();
        }
    }

    public void setInvoice(Invoice invoice) {
        if (invoice != null && !TextUtils.isEmpty(invoice.getTitle())) {
            this.mInvoice = invoice;
            mTvInvoice.setText(invoice.getTitle());
        }
    }
}
